import router from './router'
import store from '@/store'

// const getQueryString = name => {
// 	var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
// 	var r = window.location.search.substr(1).match(reg)
// 	if (r != null) {
// 		return unescape(r[2])
// 	}
// 	return null
// }
// const code = getQueryString('code')
// const state = getQueryString('state')

router.beforeEach((to, from, next) => {
	const {
		state: { isLogin },
		dispatch
	} = store
	if (!isLogin) {
		const {
			query: { code, state },
			path
		} = to
		if (code && state) {
			;(async () => {
				await dispatch('handleLoginStatus', { code, state })
				await dispatch('handleSetPayrollInfo')
				next(path)
			})()
		} else {
			to.matched.some(({ meta: { requiresAuth } }) => requiresAuth) ? next('login') : next()
			// next()
		}
	} else {
		next()
	}
})

export default router
